<template>
  <AModalPro title="选择用户" width="800px" v-bind="$attrs" :open="props.open" :maskClosable="false" :footer="false">
    <div class="content-container">
      <UserTable
        :column-selected="['index', 'userName', 'nickName', 'email', 'phoneNumber', 'createTime', 'action']"
        :data-source="sourceData"
        :loading="spinning"
        :row-selection="{ selectedRowKeys: selected.keys, onChange: (keys, rows) => setSelected({ keys, rows }) }"
        :pagination="{
          current: pagination.pageNum,
          pageSize: pagination.pageSize,
          total: pagination.total,
          onChange: onPageChange
        }"
        @search="onSearchData"
        @search-reset="onResetData"
      >
        <template #searchCollapse>
          <UserSearchFrom @finish="onSearchData" @reset="onResetData"></UserSearchFrom>
        </template>
        <template #operateLeft>
          <AButton
            type="primary"
            ghost
            :disabled="!selected.keys.length"
            :loading="loading"
            @click="() => onFinish(selected.keys, selected.rows)"
          >
            完成
          </AButton>
        </template>
        <template #operateRight>
          <ATooltip title="刷新列表">
            <AButton :icon="createVNode(ReloadOutlined)" :disabled="!!timer" @click="onRefreshData">
              {{ timer || '' }}
            </AButton>
          </ATooltip>
        </template>

        <template #bodyActionCell="{ record }">
          <AButton type="link" size="small" :loading="loading" @click="() => onFinish([record.userId], [record])">
            选择
          </AButton>
        </template>
      </UserTable>
    </div>
  </AModalPro>
</template>

<script setup>
import { createVNode, watch } from 'vue';
import { AModalPro } from '@/components/iteration';
import { UserSearchFrom, UserTable } from '../modules';
import { ReloadOutlined } from '@ant-design/icons-vue';
import { useFetchPageData, useState } from '@/hooks';

defineOptions({
  inheritAttrs: false
});

const props = defineProps({
  open: { type: Boolean, default: false },
  api: { type: Function, required: true },
  onFinish: Function
});

const [selected, setSelected] = useState({ keys: [], rows: [] });
const {
  sourceData,
  spinning: spinning,
  pagination,
  timer,
  onFetchData,
  onSearchData,
  onPageChange,
  onResetData,
  onRefreshData
} = useFetchPageData(props.api);
const [loading, setLoading] = useState(false);

watch(
  () => props.open,
  (open) => {
    open && onFetchData();
  }
);

const onFinish = async (...val) => {
  try {
    setLoading(true);
    await props.onFinish(...val);
  } catch (e) {
    await Promise.reject(e);
  } finally {
    setLoading(false);
    setSelected({ keys: [], rows: [] });
  }
};
</script>

<style lang="scss" scoped>
.content-container {
  width: 100%;
  height: 60vh;
}
</style>
